#include <pthread.h>
#include "ptfifi.h"

int cmpt = 0;

static int FIBO_SIZE;

double getTime(){
  struct timeval tv;
  gettimeofday(&tv,NULL);
  return 1000*tv.tv_sec+tv.tv_usec/1000.0;
}

int fibo (int n){

  if(n ==0){
    pthread_exit(n);
    return 0;
	}

  else if(n==1){
    pthread_exit(n);
    return 1;
 }
  else{
    int err;
    void* retval1; 
    void* retval2;
    int a = n - 1;
    int b = n - 2;

    pthread_t t1,t2;
    err=pthread_create(&t1,NULL, (void* (*)(void *))fibo,(void *) a); 
    assert(!err);
    err=pthread_create(&t2,NULL,  (void* (*)(void *))fibo, (void *)b);
    assert(!err);
    cmpt+=2;
    
    err=pthread_join(t1, &retval1);
    assert(!err);
    err=pthread_join(t2, &retval2);
    assert(!err);
/*
    if(b == FIBO_SIZE - 2)
      printf("FIBO[%d] = %g\n",b,fibtab[b]);
    if(a == FIBO_SIZE - 1)
      printf("FIBO[%d] = %g\n",a,fibtab[a]);    
    
    fibtab[*(int*)n] = fibtab[a] + fibtab[b];*/
    int temp1 = (int)retval1;
    int temp2 = (int)retval2;
    int temp3 = temp1+temp2;
    void * ret = (void *) &temp3;
    pthread_exit(temp3);
    return temp3;
  }
}

float* ptaffichage(int n){
  
  printf("\n.......Calcul de FIBO(%d) ..... \n",n); 

  /* On initialise le tableau */
  int i;
  int err;
 
  /* On calcule fibo(n) */
  void *resultat;
  double t1 = getTime();
  pthread_t thread1;
  err=pthread_create(&thread1,NULL, (void* (*)(void *))fibo,(void *)n);
    assert(!err);
  err=pthread_join(thread1 , &resultat);
    assert(!err);
  double t2 = getTime();

  /* On affiche le résultat */
  printf(".......Resultat FIBO");
  printf("[%d] = %d\n",n,(int )resultat);
  printf("   [Cout de calcul = %g ms]\n", t2 - t1);
  printf(" [Nombre de threads utilisés : %d]\n",cmpt);
  float result[2] = {t2-t1, (float)cmpt};
  return result; 
}


int main(){
  printf("Entrer un entier: \n");
  scanf("%d",&FIBO_SIZE);
  ptaffichage(FIBO_SIZE);
  return EXIT_SUCCESS;
 }

